const util = require('util')
const winston = require('winston')
const morgan = require('morgan')
const winston_mysql = require('./winston-mysql')
const morgan_json = require('morgan-json')
const response_body = require('./response_body')
const CONFIG = require('../config')
const production = (process.env.NODE_ENV || '').toLowerCase() === 'production'

// Create logger to log http requests to file and console
var logger = new winston.Logger({
  transports: [
    new winston.transports.File({
      level: 'debug',
      filename: CONFIG.log.dir + '/logs.log',
      handleExceptions: true,
      maxsize: 5242880, // 5MB
      maxFiles: 5,
      json: false,
      colorize: false
    }),
    new winston.transports.Console({
      level: 'debug',
      handleExceptions: true,
      json: false,
      colorize: true
    }),
    new winston_mysql(
      Object.assign(
        {
          table: 'server_logs'
        },
        CONFIG.mysql
      )
    )
  ],
  exitOnError: false
})

logger.stream = {
  write: function(message, encoding) {
    let object = JSON.parse(message)
    logger.info(object.message, object)
  }
}

morgan.token('req_body', function(req, res) {
  return JSON.stringify(req.body)
})

morgan.token('res_body', function(req, res) {
  return res.locals.body
})

const format = morgan_json({
  message:
    '[:date[iso]] :remote-addr - :remote-user :method :url HTTP/:http-version :status :res[content-length] :referrer :user-agent',
  user_token: ':req[authorization]',
  request_body: ':req_body',
  response_body: ':res_body',
  response_time: ':response-time[0]',
  status: ':status',
  timestamp: ':date[iso]'
})

module.exports = [response_body, morgan(format, { stream: logger.stream })]
